<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home/welcome' }"
        >首页</el-breadcrumb-item
      >
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类 -->
      <div>
        <span>选择商品分类：</span
        ><el-cascader
          v-model="goodsClassifyKeys"
          :options="goodsClassifyList"
          :props="{
            expandTrigger: 'hover',
            value: 'cat_id',
            label: 'cat_name'
          }"
          @change="selectGoodsChange"
        ></el-cascader>
      </div>
      <!-- tabs区域 -->
      <el-tabs v-model="paramsName" @tab-click="paramsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtn" @click="addBtn"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 展开项tag标签 -->
              <template slot-scope="scope">
                <el-tag
                  :key="index"
                  v-for="(item,index) in scope.row.attr_vals"
                  closable
                  @close="deleteClose(index,scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else size="small" @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="editBtn(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParamsBtn(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtn" @click="addBtn"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 展开项tag标签 -->
              <template slot-scope="scope">
                <el-tag
                  :key="index"
                  v-for="(item,index) in scope.row.attr_vals"
                  closable
                  @close="deleteClose(index,scope.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else size="small" @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="静态名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="editBtn(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParamsBtn(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加动态参数或者静态属性对话框 -->
      <el-dialog
        :title="'添加' + title"
        :visible.sync="addVisible"
        width="50%"
        :before-close="addBeforeClose"
        @close="addClose"
      >
        <!-- 表单 -->
        <el-form
          :model="addForm"
          :rules="addRules"
          ref="addFormRef"
          label-width="100px"
        >
          <el-form-item :label="title" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button type="primary" @click="addFormBtn">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑对话框 -->
      <el-dialog
        :title="'编辑' + title"
        :visible.sync="editVisible"
        width="50%"
        :before-close="editBeforeClose"
        @close="editClose"
      >
        <!-- 表单 -->
        <el-form
          :model="editForm"
          :rules="editRules"
          ref="editFormRef"
          label-width="100px"
        >
          <el-form-item :label="title" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="editFormBtn">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  getGoodsApi,
  getParamsListApi,
  getAddParamsApi,
  getEditApi,
  getDeleteParamsApi
} from '@/api/goods.js'

export default {
  name: 'Params',
  data() {
    return {
      // 商品分类数据
      goodsClassifyList: [],
      // 选择商品分类的级联选择框选中的值
      goodsClassifyKeys: [],
      // tabs显示的页面双向绑定
      paramsName: 'many',
      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],
      // 控制显示隐藏添加对话框
      addVisible: false,
      // 双向绑定添加表单的数据
      addForm: {
        attr_name: ''
      },
      // 添加表单验证
      addRules: {
        attr_name: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },
      // 控制显示隐藏编辑对话框
      editVisible: false,
      // 编辑对话框表单数据对象
      editForm: {
        attr_name: ''
      },
      // 编辑对话框表单效验
      editRules: {
        attr_name: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },
      // 当前编辑的参数id
      attrId: '',
      // 当前编辑的参数数据对象
      reserveParams: ''

    }
  },
  created() {
    this.getGoodsApi()
  },
  methods: {
    // 商品分类列表数据请求
    getGoodsApi() {
      getGoodsApi({ type: 3 }).then((res) => {
        this.goodsClassifyList = res.data.data
      })
    },
    // 参数列表数据请求
    getParamsListApi() {
      getParamsListApi({
        id: this.goodsClassifyKeys[2],
        sel: this.paramsName
      }).then((res) => {
        if (res.data.meta.status === 200) {
          this.$message.success('获取参数列表成功')
          // 循环参数列表
          res.data.data.forEach((item) => {
            // 把参数的可选项转换成数组
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
            // 添加控制显示与隐藏的值
            item.inputVisible = false
            // 添加文本框的双向绑定值
            item.inputValue = ''
          })
          // 判断是动态或者静态再赋值
          if (this.paramsName === 'many') {
            this.manyTableData = res.data.data
          } else {
            this.onlyTableData = res.data.data
          }
          return
        }
        this.$message.error('获取参数列表失败')
      })
    },
    // 添加参数请求
    getAddParamsApi() {
      getAddParamsApi(this.goodsClassifyKeys[2], {
        attr_name: this.addForm.attr_name,
        attr_sel: this.paramsName
      }).then((res) => {
        if (res.data.meta.status !== 201) {
          this.$message.error('添加参数失败')
          return
        }

        this.$message.success('添加参数成功')
        // 刷新页面数据
        this.getParamsListApi()
      })
    },
    // 编辑参数请求
    getEditApi(row) {
      getEditApi(this.goodsClassifyKeys[2], this.attrId, {
        attr_name: this.editForm.attr_name,
        attr_sel: this.paramsName,
        attr_vals: row.attr_vals.join(' ')
      }).then((res) => {
        if (res.data.meta.status !== 200) {
          this.$message.error('编辑失败')
          console.log(res)
          return
        }

        this.$message.success('编辑成功')
        this.getParamsListApi()
      })
    },
    // 删除参数请求
    getDeleteParamsApi() {
      getDeleteParamsApi(this.goodsClassifyKeys[2], this.attrId).then((res) => {
        if (res.data.meta.status !== 200) {
          this.$message.error('删除失败')
          return
        }
        this.$message.success('删除成功')
        this.getParamsListApi()
      })
    },
    // 参数展开的可选项值请求
    getParamsOptionApi(row) {
      getEditApi(this.goodsClassifyKeys[2], row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      }).then((res) => {
        if (res.data.meta.status !== 200) {
          this.$message.error('更新失败')
          return
        }

        this.$message.success('更新成功')
      })
    },
    // 监听选择商品分类的级联选择框选中项改变
    selectGoodsChange() {
      // 如果级联选中框为空，重置页面内容
      if (this.goodsClassifyKeys.length !== 3) {
        this.goodsClassifyKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      this.getParamsListApi()
    },
    // 监听tabs页面切换
    paramsClick() {
      // 有值得时候才调用请求
      if (this.goodsClassifyKeys.length) {
        this.getParamsListApi()
      }
    },
    // 点击添加对话框X触发关闭对话框
    addBeforeClose() {
      this.addVisible = false
    },
    // 点击添加参数或者属性弹出对话框触发
    addBtn() {
      this.addVisible = true
    },
    // 添加对话框的确定按钮触发
    addFormBtn() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return
        // 调用添加参数请求
        this.getAddParamsApi()
        this.addVisible = false
      })
    },
    // 关闭添加对话框重置
    addClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击编辑对话框X触发
    editBeforeClose() {
      this.editVisible = false
    },
    // 点击编辑按钮
    editBtn(row) {
      this.editVisible = true
      // 当前编辑的参数名
      this.editForm.attr_name = row.attr_name
      // 当前编辑的参数id赋值
      this.attrId = row.attr_id
      // 储存当前参数的数据对象
      this.reserveParams = row
      console.log(this.reserveParams)
    },
    // 确定编辑提交
    editFormBtn() {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return
        // 调用编辑请求
        this.getEditApi(this.reserveParams)
        this.editVisible = false
      })
    },
    // 关闭编辑对话框触发重置
    editClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 删除按钮提示框
    deleteParamsBtn(attrId) {
      // 当前删除的参数id赋值
      this.attrId = attrId.attr_id

      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 调用删除请求
          this.getDeleteParamsApi()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 删除参数的可选项触发
    deleteClose(index, row) {
      // 提示是否删除
      this.$confirm('此操作将永久删除该可选项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        // 更新参数可选项数组
        row.attr_vals.splice(index, 1)
        // 调用参数可选项请求
        this.getParamsOptionApi(row)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 按下enter或者失去input焦点触发
    handleInputConfirm(row) {
      // 判断是否填写内容，添加页面内容并发送请求
      if (row.inputValue.trim()) {
        row.attr_vals.push(row.inputValue)
        // 调用参数可选项请求
        this.getParamsOptionApi(row)
      }
      row.inputVisible = false
      row.inputValue = ''
    },
    // 点击显示添加可选项input框
    showInput(row) {
      row.inputVisible = true
      // 自动获取焦点
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed: {
    // 根据是否选中商品分类返回true和false，来控制是否显示添加参数与属性的按钮
    isBtn() {
      if (this.goodsClassifyKeys.length === 3) {
        return false
      }
      return true
    },
    // 根据不同paramsName值不同赋予不同的标题
    title() {
      if (this.paramsName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
}

.el-alert {
  margin-bottom: 15px;
}

.el-tag{
  margin: 7px;
}

.input-new-tag {
  width: 90px;
}
</style>
